export default function setShareMeta(config) {
  setWSCNShare(config)
  setWeixinShare(config)
}

function setWeixinShare(shareConfig) {
  if (!/MicroMessenger/i.test(navigator.userAgent)) return false
  var xmlhttp = new XMLHttpRequest()
  var url = 'https://api-prod.wallstreetcn.com/apiv1/user/weixin/signature?signurl=' + encodeURIComponent(window.location.origin + window.location.pathname + window.location.search)
  xmlhttp.onreadystatechange = state_Change
  xmlhttp.open('GET', url, true)
  xmlhttp.send(null)
  function state_Change() {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
        var res = JSON.parse(xmlhttp.response)
        shareWei(res.data)
      } else {
        alert("Problem retrieving XML data");
      }
    }
  }
  function shareWei(data) {
    var config = {
      appId: data.appid,
      nonceStr: data.noncestr,
      signature: data.signature,
      timestamp: data.timestamp,
      jsApiList: data.jsapis
    }
    wx.config(config)
    var title = shareConfig.title
    var desc = shareConfig.desc
    var link = shareConfig.link
    var imgUrl = shareConfig.imgUrl
    var type = shareConfig.type
    var dataUrl = shareConfig.dataUrl
    wx.ready(function () {
      wx.onMenuShareTimeline({
        title: title,
        link: link,
        imgUrl: imgUrl,
        success: function () {
          // 用户确认分享后执行的回调函数
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
        }
      })
      wx.onMenuShareAppMessage({
        title: title,
        desc: desc,
        link: link,
        imgUrl: imgUrl,
        type: type, // 分享类型,music、video或link，不填默认为link
        dataUrl: dataUrl, // 如果type是music或video，则要提供数据链接，默认为空
        success: function () {
          // 用户确认分享后执行的回调函数
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
        }
      })
      wx.onMenuShareQQ({
        title: title,
        desc: desc,
        link: link,
        imgUrl: imgUrl,
        success: function () {
          // 用户确认分享后执行的回调函数
        },
        cancel: function () {
          // 用户取消分享后执行的回调函数
        }
      })
    })
  }
}
function setWSCNShare(config) {
  var $head = document.getElementsByTagName('head')[0]
  var url = config.link
  var title = config.title
  var content = config.desc
  var image = config.imgUrl
  $head.appendChild(createMeta('wscn-share-url', url))
  $head.appendChild(createMeta('wscn-share-title', title))
  $head.appendChild(createMeta('wscn-share-content', content))
  $head.appendChild(createLink('wscn-share-image', image))
  function createMeta(name, content) {
    var html = '<meta name="' + name + '" content="' + content + '"/>'
    return createdNode(html)
  }
  function createLink(rel, href) {
    var html = '<link rel="' + rel + '" href="' + href + '"/>'
    return createdNode(html)
  }
  function createdNode(html) {
    var div = document.createElement('div')
    div.innerHTML = html
    return div.childNodes[0]
  }
}